package com.wohuijituan.whcsmerchant.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.wohuijituan.whcsmerchant.R;
import com.wohuijituan.whcsmerchant.bean.CommonBean;
import com.wohuijituan.whcsmerchant.bean.GoodsAddListBean.DataEntity.GoodsEntity;
import com.wohuijituan.whcsmerchant.bean.ShopGoodsListBean;
import com.wohuijituan.whcsmerchant.callback.CommonCallBack;
import com.wohuijituan.whcsmerchant.fragment.GoodsAddFragment;
import com.wohuijituan.whcsmerchant.fragment.GoodsSellFragment;
import com.wohuijituan.whcsmerchant.url.ParamsKey;
import com.wohuijituan.whcsmerchant.url.Urls;
import com.wohuijituan.whcsmerchant.utils.CashierInputFilter;
import com.wohuijituan.whcsmerchant.utils.ExtraName;
import com.wohuijituan.whcsmerchant.utils.LogUtils;
import com.wohuijituan.whcsmerchant.utils.MyOkHttpUtils;
import com.wohuijituan.whcsmerchant.utils.MyRequestParams;

import okhttp3.Call;

/**
 * 说明：
 * 作者：朱世元
 * 时间： 2016/9/3 13:35
 * 版本：V1.0
 * 修改历史：
 */
public class GoodsCompileActivity extends MyBaseActivity implements View.OnClickListener{
    private static final String TAG = "GoodsCompileActivity";
    private static final String PRICE = "价格";
    private static final String INTEGRAL = "积分";
    private static final String STORE = "库存量";
    private static final String BONUS = "消费奖金";
    private static final int AddGoods_OK = 150;
    private static final int EditGoods_OK = 160;
    private TextView tvGoodsName;
    private ImageView ivGoodsPicture
            ;
    private TextView tvAddPrice;
    private TextView tvCompilePrice;
    private TextView tvAddIntegral;
    private TextView tvCompileIntegral;
    private TextView tvAddStore;
    private TextView tvCompileStore;
    private TextView tvAddBonus;
    private TextView tvCompileBonus;

    private ImageButton titleGoBack;
    private TextView titleName;
    private TextView titleAction;
    private ImageLoader mImageLoader;
    private Button btnConfirm;


    private void assignViews() {
        tvGoodsName = (TextView) findViewById(R.id.tv_goods_name);
        ivGoodsPicture = (ImageView) findViewById(R.id.iv_goods_picture);
        tvAddPrice = (TextView) findViewById(R.id.tv_add_price);
        tvCompilePrice = (TextView) findViewById(R.id.tv_compile_price);
        tvAddIntegral = (TextView) findViewById(R.id.tv_add_integral);
        tvCompileIntegral = (TextView) findViewById(R.id.tv_compile_integral);
        tvAddStore = (TextView) findViewById(R.id.tv_add_store);
        tvCompileStore = (TextView) findViewById(R.id.tv_compile_store);
        tvAddBonus = (TextView) findViewById(R.id.tv_add_bonus);
        tvCompileBonus = (TextView) findViewById(R.id.tv_compile_bonus);
        titleGoBack = (ImageButton) findViewById(R.id.title_go_back);
        titleName = (TextView) findViewById(R.id.title_name);
        btnConfirm = (Button) findViewById(R.id.btn_confirm);
        titleAction = (TextView) findViewById(R.id.title_tv_action);
    }
    private MyOkHttpUtils myOkHttpUtils;
    private MyRequestParams params;
    private String serialNumber;//商品在商品库中的唯一编号
    private String shopGoodsSN;//商品在当前商家已上架列表中的唯一标示
    private GoodsEntity goodsData;
    private ShopGoodsListBean.DataEntity.GoodsEntity shopGoodsData;//
    private String from = "";//当前页面从什么地方跳转过来的
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_compile);
        assignViews();
        initData();
        initView();
        initListener();
    }
    private void initData() {
        myOkHttpUtils = new MyOkHttpUtils();
        params = new MyRequestParams();
        Intent intent = getIntent();
        from = intent.getStringExtra(ExtraName.TAG);
        mImageLoader= ImageLoader.getInstance();
        if(from.equals(GoodsAddFragment.TAG)){//
            LogUtils.e(TAG,"from:"+from);
            goodsData = (GoodsEntity) intent.getSerializableExtra(ExtraName.GOODSADD_BEAN);
            serialNumber = goodsData.getCS_GUID();//商品在商品库中的唯一标示
        }else if (from.equals(GoodsSellFragment.TAG)){
            LogUtils.e(TAG,"from:"+from);
            shopGoodsData = (ShopGoodsListBean.DataEntity.GoodsEntity) intent.getSerializableExtra(ExtraName.SHOPGOODS_BEAN);
            serialNumber = shopGoodsData.getSMC_CommGUID();//商品在商品库中的唯一标示
            shopGoodsSN = shopGoodsData.getSMC_GUID();//商品在当前商家上架商品列表中的唯一标示
        }

    }
    private void initView() {
//        titleAction.setVisibility(View.VISIBLE);
        titleGoBack.setVisibility(View.VISIBLE);
        if (from.equals(GoodsAddFragment.TAG)){
            //设置标题
            titleName.setText("添加商品");
            titleAction.setText("添加");
            //设置商品名称
            tvGoodsName.setText(goodsData.getCS_Name());
            mImageLoader.displayImage(goodsData.getCS_MainImg(),ivGoodsPicture);
        }else if (from.equals(GoodsSellFragment.TAG)){
            //设置标题
            titleName.setText("编辑商品");
            titleAction.setText("编辑");
            tvGoodsName.setText(shopGoodsData.getCS_Name());
            mImageLoader.displayImage(shopGoodsData.getCS_MainImg(),ivGoodsPicture);
            tvAddPrice.setText(shopGoodsData.getSMC_UnitPrice() + "");
            tvAddStore.setText(shopGoodsData.getSMC_StockNum() + "");
            tvAddBonus.setText(shopGoodsData.getSMC_XFJJ()+"");
            tvAddIntegral.setText(shopGoodsData.getSMC_Integral()+"");
        }


    }
    private void initListener() {
        tvCompileBonus.setOnClickListener(this);
        tvCompileIntegral.setOnClickListener(this);
        tvCompilePrice.setOnClickListener(this);
        tvCompileStore.setOnClickListener(this);
        titleGoBack.setOnClickListener(this);
        titleAction.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_compile_price://编辑价格
                showCompileDialog(PRICE);
                break;
            case R.id.tv_compile_integral:// 编辑积分
                showCompileDialog(INTEGRAL);
                break;
            case R.id.tv_compile_store://编辑库存
                showCompileDialog(STORE);
                break;
            case R.id.tv_compile_bonus:// 编辑消费奖金
                showCompileDialog(BONUS);
                break;
            case R.id.title_go_back:// 返回按钮
                onBackPressed();
                break;
            case R.id.btn_confirm:// 保存设置
                double price = Float.parseFloat(tvAddPrice.getText().toString().trim());
                double integral = Float.parseFloat(tvAddIntegral.getText().toString().trim());
                double bonus = Float.parseFloat(tvAddBonus.getText().toString().trim());
                int store = Integer.parseInt(tvAddStore.getText().toString().trim());
                if (from.equals(GoodsAddFragment.TAG)){
                    addGoodsRequest(serialNumber,price,integral,bonus,store);
                }else if (from.equals(GoodsSellFragment.TAG)){
                    editGoodsRequest(serialNumber,shopGoodsSN,price,integral,bonus,store);
                }
                break;
        }
    }

    /**
     * 从商品库中添加商品
     * @param serialNumber
     * @param price
     * @param integral
     * @param bonus
     * @param store
     */
    private void addGoodsRequest(String serialNumber,double price,double integral,double bonus,int store){
        showDialog(this);
        String strUrl = Urls. GoodsAdd;
        params.clear();
        params.addStringRequest(ParamsKey.GoodsAdd_UserKey, myApplication.getUserKey());
        params.addStringRequest(ParamsKey.GoodsAdd_Price,price+"");
        params.addStringRequest(ParamsKey.GoodsAdd_Bonus,bonus+"");
        params.addStringRequest(ParamsKey.GoodsAdd_Number,serialNumber);
        params.addStringRequest(ParamsKey.GoodsAdd_Integral,integral+"");
        params.addStringRequest(ParamsKey.GoodsAdd_Store,store+"");
        myOkHttpUtils.postRequest(strUrl, params, new CommonCallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showToast(ctx, "网络出错,请检查网络是否连接!");
                LogUtils.e(TAG, e.getMessage());
                dismissDialog();
            }

            @Override
            public void onResponse(CommonBean response, int id) {
                dismissDialog();
                if (response.getState() == 1) {
                    Message msg = new Message();
                    msg.what = AddGoods_OK;
                    handler.sendEmptyMessage(AddGoods_OK);
                    showToast(ctx, "添加成功:" + response.getMsg());
                } else {
                    showToast(ctx, "添加失败:" + response.getMsg());

                }
            }
        });
    }
    private void editGoodsRequest(String goodsSN,String shopGoodsSN,
                                  final double price, final double integral, final double bonus, final int store){
        showDialog(this);
        String strUrl = Urls.ShopGoodsEdit;
        params.clear();
        params.addStringRequest(ParamsKey.GoodsEdit_ShopNumber, myApplication.getUserKey());
        params.addStringRequest(ParamsKey.GoodsEdit_ShopGoodsNumber, shopGoodsSN);
        params.addStringRequest(ParamsKey.GoodsEdit_GoodsNumber, goodsSN);
        params.addStringRequest(ParamsKey.GoodsEdit_Bonus, bonus+"");
        params.addStringRequest(ParamsKey.GoodsEdit_Integral, integral+"");
        params.addStringRequest(ParamsKey.GoodsEdit_Store,store+"");
        params.addStringRequest(ParamsKey.GoodsEdit_Price,price+"");
        myOkHttpUtils.postRequest(strUrl, params, new CommonCallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showToast(ctx, "网络出错,请检查网络是否连接!");
                LogUtils.e(TAG, e.getMessage());
                dismissDialog();
            }

            @Override
            public void onResponse(CommonBean response, int id) {
                dismissDialog();
                if (response.getState() == 1) {
                    Message msg = new Message();
                    msg.what = EditGoods_OK;
                    Bundle data = new Bundle();
                    data.putDouble("price",price);
                    data.putDouble("integral",integral);
                    data.putDouble("bonus",bonus);
                    data.putInt("store", store);
                    msg.setData(data);
                    handler.sendMessage(msg);
                    showToast(ctx, "编辑成功:" + response.getMsg());
                } else {
                    showToast(ctx, "编辑失败:" + response.getMsg());

                }
            }
        });
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case AddGoods_OK://TODO 跳转回添加界面
                    GoodsCompileActivity.this.finish();
                    break;
                case EditGoods_OK://TODO 跳转回编辑界面
                    Bundle data = msg.getData();
                    shopGoodsData.setSMC_UnitPrice(data.getDouble("price",0));
                    shopGoodsData.setSMC_XFJJ(data.getDouble("bonus",0));
                    shopGoodsData.setSMC_Integral(data.getDouble("integral",0));
                    shopGoodsData.setSMC_StockNum(data.getInt("store",0));
                    GoodsCompileActivity.this.setResult(RESULT_FIRST_USER);
                    finish();
            }
        }
    };
    /**
     * 弹出一个dialog让用户修改信息
     * @param title
     */
    private void showCompileDialog(final String title){
        final EditText et = new EditText(this);
        et.setSingleLine(true);
        //直接调出输入数字软键盘
        et.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        //添加只能输入小数的过滤器
        InputFilter[] filters = {new CashierInputFilter()};
        et.setFilters(filters);
        new AlertDialog.Builder(this).setTitle(title)
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String input = et.getText().toString();
                        if (input.equals("")) {
                            showToast(GoodsCompileActivity.this,"输入不能为空");
                        } else {
                            changeContent(title,input);
                        }
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
    /**
     * 改变设置内容
     * @param tag 所要修改的地方
     * @param content 所要修改的内容
     */
    private void changeContent(String tag,String content){
        if (tag==PRICE){
            tvAddPrice.setText(content);
        }else if (tag==INTEGRAL){
            tvAddIntegral.setText(content);
        }else if (tag==STORE){
            tvAddStore.setText(content);
        }else if (tag==BONUS){
            tvAddBonus.setText(content);
        }
    }
}
